package com.attilax.urldsl;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.attilax.anno.Inj;
import com.attilax.html.htmlx;
import com.attilax.io.filex;
import com.attilax.ioc.IocXq214;
import com.attilax.lang.Global;
import com.attilax.lang.MapX;
import com.attilax.lang.Trigger;
import com.attilax.net.requestImp;
import com.attilax.sql.Dsl2sqlService;
import com.attilax.sql.SqlService;
import com.attilax.store.OrmStoreService;
import com.attilax.token.TokenService;
import com.attilax.user.NotLoginEx;
import com.attilax.web.ReqX;
import com.google.common.collect.Maps;
import com.google.inject.Inject;

/**
 * q317 com.attilax.urldsl.UrlDsl2SqlStoreService
 * DataService
 * @author Administrator
 *
 */
public class UrlDsl2SqlStoreService extends Dsl2sqlService {
	public static Map<String, Function> scriptMapper = Maps.newLinkedHashMap();
	{
		scriptMapper.put("txt2html", (txt) -> {
			return htmlx.txt2html(txt.toString());
		});

	}
	@Inject
	public 	SqlService sqlSrv;
	@Inject
	public Dsl2sqlService d2sSrv;
	@Inject
	public TokenService tkSrv;
	
	public Trigger trigr;

	public static void main(String[] args) {
		requestImp m = new requestImp();

		m.put("$tb", "wxb_good_copy");
		// m.put("$tabletype", "view");
		// m.put("$view_store_path","com/attilax/order");
		m.put("$op", "i");
		m.put("copy_title", "copy_title_2005");
		Global.req.set(m);
		System.setProperty("apptype", "jobus");

		// OrmStoreService ormSvr = IocXq214.getBean(OrmStoreService.class);
		UrlDsl2SqlStoreService srv = IocXq214
				.getBean(UrlDsl2SqlStoreService.class);
		// Map m=new HashMap();
		System.out.println(srv.exe());

		System.out.println("--f");

	}

	public Object exe() {

		HttpServletRequest req = Global.req.get();
		tkSrv.setModule(req.getParameter("$utype") + "Mod");
		if(req.getParameter("$trigger")!=null)   //p319
		{
			String tiggerName=req.getParameter("$trigger");
		    Object trigger= 	IocXq214.getBean(tiggerName);
		    this.trigr=(Trigger) trigger;
		}

		Map m = ReqX.toMap(req);
		if (m.get("$table") == null)
			m.put("$table", m.get("$tb"));
		if (m.get("$op").equals("i"))
			m.put("$op", "insert");
		Set<String> st = m.keySet();
		for (String k : st) {
			if (m.get(k).equals("$cur_uid")) {
				String getuid = tkSrv.getuid(req);
				if (StringUtils.isEmpty(getuid))
					throw new NotLoginEx("NotLoginEx");
				m.put(k, getuid);
			}
			if(m.get(k).toString().equals("$uuid"))
			{
				m.put(k,filex.getUUidName());
			}
		}
		//fld fun
		DslUtil.appFldFun(m);
if(trigr!=null)
	trigr.exec(m);


		String sql = d2sSrv.dsl2sql(m);
		if (StringUtils.isEmpty(sql))
			throw new RuntimeException(
					" cant convert sql str rzt is null or empty："+d2sSrv);
		return sqlSrv.exe(sql);

	}

}
